package org.zhuzx.util;

//@Deprecated//未测试
public class FrequencyDetector {
	
	private long timeSpan;
	private long[] recorder;
	private int lastIndex;
	private int cursor = 0;
	private boolean isNotFull = true;
	
	public FrequencyDetector(long timeSpan, int maxAllows) {
		this.timeSpan = timeSpan;
		this.recorder = new long[maxAllows];
		this.lastIndex = maxAllows - 1;
	}
	
	public synchronized long reckonIn() {
		long currentTime = System.currentTimeMillis();
		if (isNotFull) {
			isNotFull = ++cursor < lastIndex;
		} else {
			cursor = (cursor == lastIndex) ? 0 : (cursor + 1);
			long timeDiff = currentTime - recorder[cursor];
			if (timeDiff < timeSpan) {
				return timeSpan - timeDiff;
			}
		}
		recorder[cursor] = currentTime;
		return 0;
	}
	
}